package com.zx.idc.backend.gui.api.commom.entity.factory;

import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.common.constants.IdcCommandAckTypeConstants;
import com.zx.idc.xml.entity.idccommandack.IdcCommandAck;
import com.zx.idc.xml.entity.idccommandack.commandack.CommandAck;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import static com.zx.idc.common.attributes.SystemAttributes.COMMAND_ACK_RETURN_CODE_FAIL;
import static com.zx.idc.common.attributes.SystemAttributes.COMMAND_ACK_RETURN_CODE_OK;

/**
 * 回调结果信息工厂
 */
public class CommandAckFactory {

    /**
     * 指令成功模板，指令ID需要自己设置
     * @param idcCommandAckTypeConstants 指令回调类型
     * @param commandModel 指令模板
     * @param function CommandAck内容的特殊处理
     * @return 回调的实体
     */
    public static IdcCommandAck ackSuccess(IdcCommandAckTypeConstants idcCommandAckTypeConstants, CommandModel commandModel, Function<CommandAck, CommandAck> function) {
        //调用webService接口响应结果
        IdcCommandAck idcCommandAck = new IdcCommandAck();
        List<CommandAck> commandAcks = new ArrayList<>();
        CommandAck commandAck = success()
            .setType(idcCommandAckTypeConstants.getType());
        commandAcks.add(function.apply(commandAck));
        return idcCommandAck.setIdcId(commandModel.getIdcId())
            .setTimeStamp(LocalDateTime.now())
            .setCommandAck(commandAcks);
    }

    /**
     * 指令失败模板,指令ID需要自己设置
     *
     * @param idcCommandAckTypeConstants 指令回调类型
     * @param commandModel               指令模板
     * @param failReason                 失败原因
     * @param function                   CommandAck内容的特殊处理
     * @return 回调的实体
     */
    public static IdcCommandAck ackFail(IdcCommandAckTypeConstants idcCommandAckTypeConstants, CommandModel commandModel, String failReason, Function<CommandAck, CommandAck> function) {
        //调用webService接口响应结果
        IdcCommandAck idcCommandAck = new IdcCommandAck();
        List<CommandAck> commandAcks = new ArrayList<>();
        CommandAck commandAck = fail(failReason)
            .setType(idcCommandAckTypeConstants.getType());
        commandAcks.add(function.apply(commandAck));
        return idcCommandAck.setIdcId(commandModel.getIdcId())
            .setTimeStamp(LocalDateTime.now())
            .setCommandAck(commandAcks);
    }

    /**
     * 调用结果成功最小实体
     *
     * @return
     */
    private static CommandAck success() {
        return new CommandAck()
            .setResultCode(COMMAND_ACK_RETURN_CODE_OK)
            .setMsgInfo("成功");
    }

    /**
     * 调用结果失败最小实体
     *
     * @param failReason 错误的原因
     * @return
     */
    private static CommandAck fail(String failReason) {
        return new CommandAck()
            .setResultCode(COMMAND_ACK_RETURN_CODE_FAIL)
            .setMsgInfo(failReason);
    }
}
